package com.mingke.java.AIO;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @author mingke
 * @function AIO读出信息的回调
 * @date 2021/11/9
 */
public class AIOReadHandler implements CompletionHandler<Integer, ByteBuffer> {

    @Override
    public void completed(Integer result, ByteBuffer buffer) {
        if(result == -1) {
            System.out.println("断开连接");
        }else {
            buffer.flip();
            int bufferLength = buffer.limit();
            byte bytes[] = new byte[bufferLength];
            buffer.get(bytes, 0, bufferLength);
            System.out.println("数据长度为："+bufferLength+" 数据内容如下");
            for(int i = 0; i < bufferLength; i++) {
                if(i == bufferLength-1) {
                    System.out.print(bytes[i] + "\n");
                }else {
                    System.out.print(bytes[i] + " ");
                }
            }
            buffer.clear();
        }
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        try {
            exc.printStackTrace();
        }finally {
            System.out.println("结束了");
        }
    }
}
